package cn.czh.user.service.impl;

import cn.czh.basic.constant.VerifyCodeConstant;
import cn.czh.basic.exception.BusinessException;
import cn.czh.basic.util.AjaxResult;
import cn.czh.basic.util.HttpUtil;
import cn.czh.basic.util.Md5Utils;
import cn.czh.basic.util.StrUtils;
import cn.czh.system.domain.Menu;
import cn.czh.system.mapper.MenuMapper;
import cn.czh.system.mapper.PermissionMapper;
import cn.czh.user.constant.WxConstants;
import cn.czh.user.domain.Logininfo;
import cn.czh.user.domain.User;
import cn.czh.user.domain.Wxuser;
import cn.czh.user.dto.LoginDto;
import cn.czh.user.jwt.JwtUtils;
import cn.czh.user.jwt.LoginData;
import cn.czh.user.jwt.RsaUtils;
import cn.czh.user.mapper.LogininfoMapper;
import cn.czh.user.mapper.UserMapper;
import cn.czh.user.mapper.WxuserMapper;
import cn.czh.user.service.ILogininfoService;
import cn.czh.basic.service.impl.BaseServiceImpl;
import com.alibaba.fastjson.JSONObject;
import com.sun.mail.imap.protocol.ID;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.net.URL;
import java.security.PrivateKey;
import java.sql.Struct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 业务实现类：
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private LogininfoMapper logininfoMapper;

    @Autowired
    private WxuserMapper wxuserMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private MenuMapper menuMapper;

    @Override
    public AjaxResult accountLogin(LoginDto loginDto) {
        String account = loginDto.getAccount();
        String inputPwd = loginDto.getCheckPass();
        Integer type = loginDto.getType();
        //1.校验 -- 空值校验
        if (StringUtils.isEmpty(account) || StringUtils.isEmpty(inputPwd)) {
            throw new BusinessException("登录信息不能为空");
        }

        //2.校验 -- 账号校验
        Logininfo logininfo = logininfoMapper.loadByAccount(loginDto);
        if (logininfo == null) { //没有查询到登录信息 -- 账号错误
            throw new BusinessException("账号有误");
        }

        //3.校验密码
        String dbPwd = logininfo.getPassword(); //数据库中加密的密码
        String inputMd5Pwd = Md5Utils.encrypByMd5(inputPwd + logininfo.getSalt());
        if (!dbPwd.equals(inputMd5Pwd)) {
            throw new BusinessException("密码有误");
        }

        Map<String, Object> map = loginSuccessJwtHandler(logininfo);
        //6.响应数据
        return AjaxResult.me().setResultObj(map);

    }

    private Map<String, Object> loginSuccessJwtHandler(Logininfo logininfo) {
        try {
            Map<String,Object> map = new HashMap<>();
            //细节：如果是管理员才需要加四个数据，如果是用户只需要：登录信息对象，jwt串【1,4】
            //一：想办法获取四个数据
            //1.登录信息对象 - 在参数中
            map.put("logininfo",logininfo);
            LoginData loginData = new LoginData();
            loginData.setLogininfo(logininfo);
            if(logininfo.getType()==0){//后台管理员
                //2.当前登录人的所有权限的sn集合
                List<String> permissions = permissionMapper.loadPermissionSnByLogininfoId(logininfo.getId());
                map.put("permissions",permissions);
                loginData.setPermissions(permissions);
                //3.当前登录人的所有二级菜单及其它的父级菜单【前端需要
                List<Menu> menus = menuMapper.loadMenusByLogininfoId(logininfo.getId());
                map.put("menus",menus);
                loginData.setMenus(menus);
            }
            //4.将以上三个数据装到LoginData  - 使用工具类进行加密【1 2】 - jwt串
            PrivateKey privateKey = RsaUtils.getPrivateKey(JwtUtils.class.getClassLoader().getResource("auth_rsa.pri").getFile());
            String jwtToken = JwtUtils.generateTokenExpireInMinutes(loginData, privateKey, 30000);//没有做刷新过期时间

            //二：将四个数据装到map进行返回。疑问：jwt串里面不是已经有登录信息，权限和菜单了吗？ - 前端没有做解密
            map.put("token",jwtToken);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  null;
    }

    @Override
    public AjaxResult wechatLogin(String code) {
        //1.准备发送第二个请求的参数：
        String url = WxConstants.GET_ACK_URL.replace("APPID", WxConstants.APPID)
                .replace("SECRET", WxConstants.SECRET)
                .replace("CODE", code);
        //2.发送请求 - 返回json格式的数据
        String jsonStr = HttpUtil.httpGet(url);
        //3.将json格式的字符串转成json对象 -- 为了获取token和openid
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        String accessToken = jsonObject.getString("access_token");
        String openId = jsonObject.getString("openid");
        //4.通过openid查询数据库
        Wxuser wxuser = wxuserMapper.loadByOpenId(openId);
        //4.1如果查询到了并且user_id有值 -- 说明以前绑定过 -- 免密登录
        if (wxuser != null && wxuser.getUserId() != null && userMapper.loadById(wxuser.getUserId()) != null) { //三个都成立才说明绑定过


            User user = userMapper.loadById(wxuser.getUserId());
            Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());


            Map<String, Object> map = loginSuccessJwtHandler(logininfo);
            map.put("wxuser",wxuser);
            //响应数据
            return AjaxResult.me().setResultObj(map);

        } else {
            //4.2没有查询到响应给前端进行跳转 = 设置success=false，并且将token和openid传递给前端
            String param = "?accessToken=" + accessToken + "&openId=" + openId;
            return AjaxResult.me().setSuccess(false).setResultObj(param);
        }
    }

    @Override
    public AjaxResult wechatBinder(Map<String, String> map) {
        String phone = map.get("phone");
        String verifyCode = map.get("verifyCode");
        String accessToken = map.get("accessToken");
        String openId = map.get("openId");
        //1.校验 -- 非空校验
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(verifyCode)) {
            throw new BusinessException("信息不能为空");
        }

        //2.校验 -- 手机验证码是否过期，是否正确
        Object obj = redisTemplate.opsForValue().get(VerifyCodeConstant.BINDER_CODE_PREFIX + phone);
        if (obj == null) { //如果没有说明已过期
            throw new BusinessException("验证码已过期");
        }
        //redis保存的验证码和用户输入的验证码作比较 -- 判断验证码是否正确
        if (!obj.toString().split(":")[0].equals(verifyCode)) {
            throw new BusinessException("验证码错误");
        }

        //3.通过ack和openid发送第三个请求
        String url = WxConstants.GET_USER_URL.replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String jsonStr = HttpUtil.httpGet(url);   //发送请求 -- 返回json格式的字符串(格式)
        //4.处理响应的数据：json字符串 - json对象 - 获取wxUser的信息
        Wxuser wxuser = jsonStr2Wxuser(jsonStr);

        //5.绑定用户：将WxUser对象【第三个请求中获取】 与 User对象【通过手机创建】进行绑定
        User user = userMapper.loadByPhone(phone);
        if (user == null) { //根据电话没有找到user对象
            //通过phone创建User对象
            user = phone2User(phone);
            Logininfo logininfo = user2Logininfo(user);

            logininfoMapper.save(logininfo);
            user.setLogininfoId(logininfo.getId());
            userMapper.save(user);
        }
        //user一定会有。并且user_id也有
        wxuser.setUserId(user.getId());
        wxuserMapper.save(wxuser);

        //做免密登录：token，logininfo对象
        Logininfo logininfo = logininfoMapper.loadById(user.getLogininfoId());

        Map<String, Object> mapTmp = loginSuccessJwtHandler(logininfo);
        mapTmp.put("wxuser",wxuser);

        return new AjaxResult().setResultObj(mapTmp);
    }

    //关联
    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User phone2User(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        //随机密码
        String randomPwd = StrUtils.getComplexRandomString(6);
        String md5Pwd = Md5Utils.encrypByMd5(randomPwd + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        user.setState(1);

        return user;
    }

    private Wxuser jsonStr2Wxuser(String jsonStr) {
        JSONObject jsonObject = JSONObject.parseObject(jsonStr);
        Wxuser wxuser = new Wxuser();
        wxuser.setOpenid(jsonObject.getString("openid"));
        wxuser.setNickname(jsonObject.getString("nickname"));
        wxuser.setSex(jsonObject.getInteger("sex"));
        wxuser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxuser.setUnionid(jsonObject.getString("unionid"));

        String country = jsonObject.getString("country");
        String province = jsonObject.getString("province");
        String city = jsonObject.getString("city");

        wxuser.setAddress(country + province + city);
        return wxuser;
    }
}
